package iscript.gameFramework.NetService.data
{
	import flash.events.EventDispatcher;
	import flash.utils.ByteArray;
	import flash.utils.Dictionary;
	import iscript.coreFramework.debug.ArthropodDebug;
	import iscript.coreFramework.reflect.getClassPackage;
	import iscript.coreFramework.reflect.getClassPath;
	import iscript.gameFramework.NetService.core.ServiceEvent;
	import iscript.gameFramework.NetService.ServiceProxy;
	
	public class BufferList
	{
		
		public function BufferList()
		{
		
		}
		private var _data:Vector.<NetMessageBase> = new Vector.<NetMessageBase>;
		static private var _instance:BufferList = new BufferList();
		
		static public function getInstance():BufferList
		{
			return _instance;
		}
		
		static private var _commandlist:Dictionary;
		
		public function loadCommandList(command:Dictionary):void
		{
			_commandlist = command;
		}
		
		public function add(data:ByteArray):void
		{
			if (_commandlist == null)
				throw new Error("use method loadCommandList");
			var newMsg:NetMessageBase = new NetMessageBase()
			newMsg.parse(data);
			var commandName:String = newMsg.MainId + "-" + newMsg.ChildId
			data.position = 0;
			
			if (_commandlist[commandName] == null)
				throw new Error("CommandList:" + commandName + " 没有注册");
			
			if (_commandlist[commandName] != NetMessageBase.Empty)
			{
				var _class:NetMessageBase = new (_commandlist[commandName]);
				_class.parse(data);
				_data.push(_class);
				/*if (commandName == "3-14") {
					ArthropodDebug.warning("ADD Buffer" + commandName);
					}*/
			}
		}
		
		/**
		 * 发送用户已注册的包，未注册的包保留。
		 */
		public function sendOnce():void
		{
			if (hasBuffer())
			{
				var currentIndex:int = -1;
				for (var i:int = 0; i < _data.length; i++)
				{
					if (ServiceProxy.instance.watchServiceEventPool.isRegisterBycommandName(_data[i].MainId + "-" + _data[i].ChildId))
					{
						var event:ServiceEvent = new ServiceEvent(_data[i]);
						event.commandName = _data[i].MainId + "-" + _data[i].ChildId;
						/* if (event.commandName == "3-14") {
							ArthropodDebug.warning("SEND" + event.commandName);
							}*/
						ServiceProxy.instance.dispatchEvent(event);
						currentIndex = i;
						
						break;
					}
				}
				if (currentIndex != -1)
				{
					_data.splice(currentIndex, 1);
				}
				
			}
		}
		
		public function hasBuffer():Boolean
		{
			return _data.length > 0;
		}
	}

}